package com.kinyx.framework.jexl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.jexl3.JexlBuilder;
import org.apache.commons.jexl3.JexlContext;
import org.apache.commons.jexl3.JexlEngine;
import org.apache.commons.jexl3.MapContext;

import com.kinyx.framework.annotation.assist.CanNotNull;
import com.kinyx.framework.annotation.assist.ReturnNotNull;
import com.kinyx.framework.annotation.assist.ReturnNull;
import com.kinyx.framework.annotation.assist.Tester;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

/**
 * 执行表达式工具类
 */
@Tester("com.kinyx.framework.jexl.KJexlUtils_Tester_")
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class KJexlUtils {

	/**
	 * 执行表达式
	 * @param params 参数
	 * @param codes 代码
	 * @return 执行结果
	 */
	@ReturnNotNull
	public static List<Object> evaluate(@CanNotNull final Map<String, Object> params, @CanNotNull final List<String> codes) {
		// 环境准备
		final JexlEngine jexlEngine = new JexlBuilder().create();
		final JexlContext jexlContext = new MapContext(params);
		// 执行代码并返回结果
		final List<Object> results = new ArrayList<>();
		codes.forEach(code -> {
			results.add(jexlEngine.createExpression(code).evaluate(jexlContext));
		});
		return results;
	}

	/**
	 * 执行表达式
	 * @param params 参数
	 * @param code 代码
	 * @return 执行结果
	 */
	@ReturnNull("代码执行为void返回值")
	@ReturnNull("代码执行结果的返回值为null")
	public static Object evaluate(@CanNotNull final Map<String, Object> params, @CanNotNull final String code) {
		// 环境准备
		final JexlEngine jexlEngine = new JexlBuilder().create();
		final JexlContext jexlContext = new MapContext(params);
		// 执行代码并返回结果
		return jexlEngine.createExpression(code).evaluate(jexlContext);
	}

}
